<?php
require_once(PATH_GI_HELPER . "Html.php");
class Helper_Template{
	protected $file = '';
	protected $html = '';
	protected $temp = '';
	protected $_config = array('cache' => true);
	
	public function __construct() {
	}

	public function html($html, $temp) {
		$this -> html = $html;
		$this -> temp = $temp;
		return $this;
	}
	
	public function file($file, $temp) {
		if (is_file($file)) {
			$this -> file = $file;
			$this -> html = file_get_contents($file);
		} else {
			_halt("$file: 文件不存在,或者无法正常读取");
		} 
		$this -> temp = $temp;
		return $this;
	}

	public function parse() {
		if ($this -> _config['cache'] && $this -> temp) {
			if (is_file($this -> temp) && filemtime($this -> temp) > filemtime($this -> file)) {
				return $this -> temp;
			} 
		} 
		$this -> html = $this -> parseLable($this -> html);
		_writeFile($this -> temp, $this -> html);
		return $this -> temp;
	}

	/**
	 * 解析模板标签
	 * 变量	<?=$var?>			=>	<?php echo $var?> 兼容短标签
	 * 变量	{$var}			=>	<?php echo $var?>
	 * 函数  {#myfunc($par)#}=>	<?php echo 	myfunc($par)?>
	 * 常量	{#URL_WEB#}=>	<?php echo URL_WEB?>
	 * 条件判断	<!--#if(condition)#--><!--#else#--><!--#elseif#-->
	 * 循环		<!--#loop $array $value#-->  <!--#loop $array $key $value#-->
	 * 结束循环	<!--#end#-->
	 * php块		<!--# print_r($var);phpinfo(); #-->
	 * @param string $html
	 * @return string
	 */
	public function parseLable($html = '') {
		$a1 = array('/<\?=/', '/\{\s*\$([\w\'\"\[\]\$\-\>\x7f-\xff]+)\s*\}/', '/\{\s*#([^-][^}]+?)\s*#\}/', '/<!--#\s*if\s*(.+?)\s*#-->/', '/<!--#\s*else\s*#-->/', '/<!--#\s*elseif\s*(.+?)\s*#-->/', '/<!--#\s*loop\s+(\S+)\s+(\S+)\s*#-->/', '/<!--#\s*loop\s+(\S+)\s+(\S+)\s+(\S+)\s*#-->/', '/<!--#\s*end\s*#-->/', '/<!--#(.+?)#-->/is');
		$a2 = array('<?php echo ',"<?php echo \$\\1?>", "<?php echo \\1?>", "<?php if(\\1){?>", "<?php } else{?>", "<?php } elseif(\\1){?>", "<?php foreach(\\1 as \\2){?>", "<?php foreach(\\1 as \\2 => \\3){?>", "<?php }?>", "<?php\n\\1\n?>");
		$html = preg_replace($a1, $a2, $html);
		$l = '/((\$[\w\x7f-\xff]*)(\[[\w\-\.\"\'\[\]\$\x7f-\xff]+\])+?)/s';
		$html = preg_replace_callback($l, array(__CLASS__, 'addquote'), $html);
		$html = "<?php !defined('PATH_APP') && die('Forbidden!');?>\n" . $html;
		return $html;
	}
	
	public function addquote($var) {
		$var = $var[0];
		return preg_replace("/\[([\w\-\.\x7f-\xff]+)\]/s", "['\\1']", $var);
	} 
} 